package com.kredit.kotlin.firebase

import android.content.Context
import android.os.Handler
import android.util.Log
import com.flashcash.solu.common.network.ServiceGenerator
import com.flashcash.solu.common.network.UserApi
import okhttp3.ResponseBody
import rx.Observable
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

object FirebaseUtil {

    private var sHandler: Handler? = Handler()

    @JvmStatic
    fun uploadFirebaseToken(token: String): Observable<ResponseBody>? {
        var userApi: UserApi? = ServiceGenerator.createService(UserApi::class.java)
        return userApi?.uploadFirebaseToken(token)
    }

    @JvmStatic
    fun getFirebaseToken(context: Context): String? {
        val sp = context.getSharedPreferences(SimpleFirebaseMessagingService.SP_FIREBASE_TOKEN, Context.MODE_PRIVATE)
        return sp.getString(SimpleFirebaseMessagingService.SP_FIREBASE_TOKEN, null)
    }

    @JvmStatic
    fun saveFirebaseToken(context: Context, token: String) {
        val pref = context.getSharedPreferences(SimpleFirebaseMessagingService.SP_FIREBASE_TOKEN, Context.MODE_PRIVATE)
        pref.edit().putString(SimpleFirebaseMessagingService.SP_FIREBASE_TOKEN, token).commit()
    }

    @JvmStatic
    fun uploadFirebaseTokenWithRetry(token: String) {
        uploadFirebaseToken(token)?.subscribeOn(Schedulers.io())?.observeOn(AndroidSchedulers.mainThread())?.subscribe(object : Observer<ResponseBody> {
            override fun onError(e: Throwable?) {
                sHandler?.postDelayed({
                    uploadFirebaseTokenWithRetry(token)
                }, 3000)
            }

            override fun onNext(t: ResponseBody?) {
                Log.i("FirebaseUtil", "Upload Firebase token success token = $token. Response body $t")
            }

            override fun onCompleted() {
            }
        })
    }

    @JvmStatic
    fun stopAll() {
        sHandler?.removeCallbacksAndMessages(null)
        sHandler = null
    }

    @JvmStatic
    fun resume() {
        sHandler?.removeCallbacksAndMessages(null)
        sHandler = Handler()
    }
}